package com.liqi.display.api;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/display/websocket/{terminalNo}")
public class LiqiWebsocket
{
    private static final Logger LOGGER = LoggerFactory.getLogger(LiqiWebsocket.class);

    private static int onlineCount = 0;

    private static CopyOnWriteArraySet<LiqiWebsocket> webSocketSet = new CopyOnWriteArraySet();

    private static Map<String, LiqiWebsocket> clients = new ConcurrentHashMap();

    private Session session;

    private String terminalNo = "";

    @OnOpen
    public void onOpen(Session session, @PathParam("terminalNo") String terminalNo)
    {
        this.session = session;
        webSocketSet.add(this);
        clients.put(terminalNo, this);
        addOnlineCount();
        LOGGER.info("设备号为:" + terminalNo + "的终端设备已被监听,当前在线设备数为:" + getOnlineCount());
        this.terminalNo = terminalNo;
    }

    @OnClose
    public void onClose()
    {
        webSocketSet.remove(this);
        clients.remove(this.terminalNo);
        subOnlineCount();
        LOGGER.info("设备号为:" + this.terminalNo + "的终端设备已被移除,当前在线设备数为:" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session)
    {
        for (LiqiWebsocket item : webSocketSet)
            try {
                Map datas = new HashMap();
                datas.put("msg", "回复终端设备号为:" + terminalNo + "的终端设备已打开成功!");
                item.sendMessage(JSON.toJSONString(datas));
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    @OnError
    public void onError(Session session, Throwable error)
    {
        LOGGER.error("终端设备号为:" + this.terminalNo + "的终端设备发生异常！");
        error.printStackTrace();
    }

    public void sendMessage(String message)
            throws IOException
    {
        this.session.getBasicRemote().sendText(message);
    }

    public static void sendMsg(Object[] message)
            throws IOException
    {
        LOGGER.info("向所有终端设备发送消息！");
        for (LiqiWebsocket item : webSocketSet)
            try {
                Map datas = new HashMap();
                datas.put("urls", message);
                item.sendMessage(JSON.toJSONString(datas));
            }
            catch (IOException e)
            {
                LOGGER.error("向所有终端设备发送消息发生异常！");
            }
    }

    public static synchronized int getOnlineCount()
    {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        onlineCount += 1;
    }
    public static synchronized void subOnlineCount() {
        onlineCount -= 1;
    }
}
